package com.xwj.nio;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

/**
 * nio文件上传
 * @author xwj
 * @date 2020/3/12
 */
public class NioUploadFileDemo {
    public static void main(String[] args) {

    }

    /**
     * 非阻塞io上传文件
     *
     * @param file
     * @param basePath
     * @return
     */
    public static String nioUpload(MultipartFile file, String basePath) {
        try {
            String filename = rename(file);
            createFileDir(basePath);
            String fullPath = basePath + filename;
            Path target = Files.createFile(Paths.get(fullPath));
            Files.copy(file.getInputStream(), target, StandardCopyOption.REPLACE_EXISTING);
            return fullPath;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 文件重命名
     *
     * @param file
     * @return
     */
    private static String rename(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());
        String filename = UUID.randomUUID().toString() + "." + suffix;
        return filename;
    }

    /**
     * 创建文件目录
     *
     * @param basePath
     */
    private static void createFileDir(String basePath) {
        File fileDir = new File(basePath);
        if (!fileDir.exists())
            fileDir.mkdirs();
    }

}
